package com.ruoyi.location.repository.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Component
@Slf4j
public class OssRepository {
    @Value("${aliyun.oss.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.bucket-name}")
    private String bucketName;

    @Value("${aliyun.oss.region}")
    private String region;

    @Value("${aliyun.accessKey}")
    private String accessKey;

    @Value("${aliyun.accessSecret}")
    private String accessSecret;

    private OSS ossClient;

    @PostConstruct
    public void init() {
        try {
            // System.setProperty("OSS_ACCESS_KEY_ID", accessKey);
            // System.setProperty("OSS_ACCESS_KEY_SECRET", accessSecret);

            ossClient = new OSSClientBuilder().build(endpoint, accessKey, accessSecret);

            // EnvironmentVariableCredentialsProvider credentialsProvider =
            //         CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // ossClient = OSSClientBuilder.create()
              //       .endpoint(endpoint)

                    // .credentialsProvider(credentialsProvider)
                    // .region(region)
                //    .build();
        } catch (Exception e) {
            log.error("初始化 OSS 客户端失败", e);
            throw new RuntimeException("初始化 OSS 客户端失败", e);
        }
    }

    @PreDestroy
    public void destroy() {
        if (ossClient != null) {
            ossClient.shutdown();
        }
    }

    /**
     * 上传头像文件到 OSS
     * @param file 文件
     * @param objectName 上传到oss的名称
     * @return 文件访问URL
     */
    public String uploadAvatar(MultipartFile file, String objectName) {
        String originalFilename = file.getOriginalFilename();
        String extension = getFileExtension(originalFilename);
        objectName = objectName + extension;

        try {
            // 上传文件
            ossClient.putObject(bucketName, objectName, file.getInputStream());

            // 生成访问URL（默认公开访问）
            return String.format("https://%s.%s/%s", bucketName, endpoint, objectName);
        } catch (Exception e) {
            log.error("上传头像到 OSS 失败", e);
            throw new RuntimeException("上传头像失败", e);
        }
    }

    /**
     * 删除旧的头像文件
     * @param avatarUrl 旧的头像URL
     */
    public void deleteOldAvatar(String avatarUrl) {
        if (StringUtils.isEmpty(avatarUrl)) {
            return;
        }

        try {
            String objectName = avatarUrl.substring(avatarUrl.indexOf(bucketName) + bucketName.length() + 1);
            ossClient.deleteObject(bucketName, objectName);
        } catch (Exception e) {
            log.error("删除旧头像失败", e);
            // 这里只记录日志，不抛出异常，避免影响主流程
        }
    }

    private String getFileExtension(String filename) {
        if (filename == null) {
            return ".jpg";
        }
        int lastDotIndex = filename.lastIndexOf(".");
        return lastDotIndex == -1 ? ".jpg" : filename.substring(lastDotIndex);
    }
}
